from . import db, login_manager
from flask_login import UserMixin
import werkzeug.security as ws

class User(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True, nullable=False, index=True)
    password = db.Column(db.String(255), nullable=False)
    role = db.Column(db.String(100), nullable=False, default='guest')

    def set_password(self, password):
        self.password = ws.generate_password_hash(password)
    def check_password(self, password):
        return ws.check_password_hash(self.password, password)

class Major(db.Model):
    __tablename__ = 'majors'
    id = db.Column(db.Integer, primary_key=True)
    major_name = db.Column(db.String(100), unique=True, nullable=False, index=True)
    students = db.relationship('Basicinfo', backref='major', lazy='dynamic')

class Basicinfo(db.Model):
    __tablename__ = 'Basicinfo'
    id = db.Column(db.Integer, primary_key=True)
    studentName = db.Column(db.String(255))
    studentBirth = db.Column(db.String(255))
    isMale = db.Column(db.Boolean)
    major_id = db.Column(db.Integer, db.ForeignKey('majors.id'))

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))